﻿#include "ssWsppSession.h"
#include "message/ssMsgIdDef.h"
#include "../ssServerErrorDefine.h"
#include "message/ssNetMsgHead.h"
#include "log/ssLogThread.h"

namespace StarSeeker
{

ssWsppSession::ssWsppSession()
{
	m_timeCheck = false;
	m_lastTime = 0;
	m_fastCount = 0;
	m_checkCount = 20;
	m_intervalTime = 100;
	m_sessionID = 0;
	m_isConnect = false;
	m_socket = 0;
	m_pNetwork = 0;
}
ssWsppSession::~ssWsppSession()
{
}

void ssWsppSession::Init(u32 id, websocketpp::connection_hdl hdl, asio::ip::tcp::socket* s, ssWsppBase* pNetwork)
{
	m_sessionID = id;
	m_lastTime = 0;
	m_fastCount = 0;
	m_isConnect = false;
	m_pNetwork = pNetwork;
	m_hdl = hdl;
	m_socket = s;
}

void ssWsppSession::SetTimeCheck(bool timeCheck, i64 intervalTime, u16 checkCount)
{
	m_timeCheck = timeCheck;
	m_intervalTime = intervalTime;
	m_checkCount = checkCount;
}

bool32 ssWsppSession::OnReceive(ssNetMsgHead* head)
{
	if (!m_isConnect)
	{
		return SS_DISCONNECT;
	}

	if (m_timeCheck)
	{
		i64 now = ssTime::GetTimeNowMS().i64p;
		if (now - m_lastTime < m_intervalTime)//太频繁
		{
			++m_fastCount;
		}
		else
		{
			m_fastCount = 0;
		}
		m_lastTime = now;
		if (m_fastCount > m_checkCount)//超过20次断线
		{
			//OnTimeCheck(m_fastCount);
			return SS_CONNECT_FAST;
		}
	}
	if (head)
	{
		//check msg
		if (head->m_dwTcpFlag != MSG_HEADER_FLAG || head->m_dwLen >= MSG_MAX_SIZE || head->m_dwLen < sizeof(ssNetMsgHead))
		{
			return SS_ILLEGAL_MSG;
		}
	}
	else
	{
		return SS_ILLEGAL_MSG;
	}
	return SS_SUCCESS;
}

const char* ssWsppSession::GetIp()
{
	if (m_ip.Length()==0)
	{
		return 0;
	}
	return m_ip.GetString();
}

void ssWsppSession::OnOpen()
{
	m_ip.Empty();
	if (m_socket)
	{
		try
		{
			asio::error_code err;
			asio::ip::tcp::socket::endpoint_type ep = m_socket->remote_endpoint(err);
			if (err.value()==0)
			{
				m_isConnect = true;
				m_ip = ep.address().to_string().c_str();
			}
			else
			{
				SS_LOG->Error("ssWsppSession::OnOpen ip error");
			}
		}
		catch (asio::system_error & e)
		{
			SS_LOG->ErrorEx("ssWsppSession::OnOpen ip error:%s", e.what());
		}
		catch (...)
		{
			SS_LOG->Error("ssWsppSession::OnOpen ip error catched");
		}
	}
}

bool ssWsppSession::IsConnected()
{
	return m_isConnect;
}

void ssWsppSession::OnTimeCheck(u16 fastCount)
{
	//CloseSocket(SS_CONNECT_FAST, "send fast");
}

}
